package http

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var client = http.Client{
	Timeout: 10 * time.Second,
}

// post 请求，json通讯
func HttpPostJson(url string, data interface{}, result interface{}, header map[string]string) ([]byte,error) {
	buf := bytes.NewBuffer(nil)
	encoder := json.NewEncoder(buf)
	if err := encoder.Encode(data); err != nil {
		return nil,err
	}

	request, err := http.NewRequest(http.MethodPost, url, buf)
	if err != nil {
		return nil,err
	}

	request.Header.Add("Content-Type", "application/json")
	if header != nil {
		for k, v := range header {
			request.Header.Add(k, v)
		}
	}

	response, err := client.Do(request)
	if err != nil {
		return nil,err
	}
	defer response.Body.Close()
	respBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil,err
	}

	return respBody,nil
}


func HttpPostForm(posturl string, data url.Values, result interface{}, host string) (error,[]byte) {
	request, err := http.NewRequest(http.MethodPost, posturl, strings.NewReader(data.Encode()))
	if err != nil {
		return err,nil
	}

	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	//request.Host = host

	resp, err := client.Do(request)
	if err != nil {
		return err,nil
	}
	defer resp.Body.Close()

	//decoder := json.NewDecoder(resp.Body)
	//if err = decoder.Decode(&result); err != nil {
	//	return err,nil
	//}
	respBody, err := ioutil.ReadAll(resp.Body)

	return nil,respBody
}


func  GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}